#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# A Twitter CLI using the python-twitter API and termcolor by Konstantin Lepa.
# First, you need to register your own app in Twitter and change CONSUMER_KEY
# and CONSUMER_SECRET. With your personal access tokens change ACCESS_TOKEN_KEY
# and ACCESS_TOKEN_SECRET.
#
# Author:  César Bustíos <cesarbustios@gmail.com>

import sys
import twitter
from termcolor import colored


# Change with your own information
CONSUMER_KEY = None
CONSUMER_SECRET = None
ACCESS_TOKEN_KEY = None
ACCESS_TOKEN_SECRET = None

TWITTER_URL = 'http://www.twitter.com/'
HOME_HEADERS = ['Timeline', '@Mentions', 'Retweets', 'Searches', 'Lists']
PROFILE_HEADERS = ['Tweets', 'Favorites', 'Following', 'Followers', 'Lists']
FLAGS = ['-p', '--post', '-t', '--timeline', '-f', '--friends-timeline',
         '-m', '--mentions', '--followers', '--friends']
         
HELP = '''
usage:\n
       --followers [<quantity>]     Show your followers
       --friends [<quantity>]       Show your friends
  -f,  --friends-timeline           Show friends status messages (including yours)
  -h,  --help                       Show this information
  -m,  --mentions                   Show your mentions
  -p,  --post <message>             Post a status message
  -t,  --timeline                   Show your status messages
'''


def get_headers(main_header, home=False, profile=False):
    headers = HOME_HEADERS if home == True else PROFILE_HEADERS
    result = '\n'
    for header in headers:
        if header == main_header:
            result += colored(header, 'blue', attrs=['underline']) + ' '
        else:
            result += colored(header, 'white', attrs=['underline']) + ' '
    return result + '\n'


def show_timeline(timeline, main_header):
    if main_header in HOME_HEADERS:
        print get_headers(main_header, home=True)
    else:
        print get_headers(main_header, profile=True)
        
    for entry in timeline:
        print colored(entry.user.screen_name, 'cyan') + ': ' + entry.text + \
              ' (' + entry.relative_created_at + ')'
    print


def show_mentions(mentions):
    print get_headers('@Mentions', home=True)
    for mention in mentions:
        print colored(mention.user.screen_name, 'cyan') + ': ' + \
              mention.text + ' (' + mention.relative_created_at + ')'
    print


def show_followers_or_friends(dudes, quantity=None):
    print colored('\nPeople(' + str(len(dudes)) + ')\n', 'blue',
                  attrs=['underline'])
    if not quantity:
        quantity = len(dudes)
        
    for dude in dudes[:quantity]:
        try:
            last_tweet = dude.GetStatus().text
        except AttributeError:
            if dude.GetProtected():
                last_tweet = colored('Tweets protected', 'red')
            else:
                last_tweet = colored('No tweets', 'red')
        print colored(dude.GetScreenName(), 'cyan') + ' (' + dude.GetName() \
              + '): ' + TWITTER_URL + dude.GetScreenName()
    print
    

def parse_flag(args):
    API = twitter.Api(consumer_key=CONSUMER_KEY,
                  consumer_secret=CONSUMER_SECRET,
                  access_token_key=ACCESS_TOKEN_KEY,
                  access_token_secret=ACCESS_TOKEN_SECRET)
    CREDENTIALS = API.VerifyCredentials()
    
    if args[1] in ['-h', '--help']:
        show_help()
    elif args[1] in ['-p', '--post']:
        message = ' '.join(args[2:])
        info_message('\nUpdating your status...\n')
        status = API.PostUpdate(message)
        timeline = API.GetUserTimeline(CREDENTIALS.screen_name,
                                       include_rts=True)
        show_timeline(timeline[:5], 'Tweets')
    elif args[1] in ['-t', '--timeline']:
        timeline = API.GetUserTimeline(CREDENTIALS.screen_name,
                                       include_rts=True)
        show_timeline(timeline, 'Tweets')
    elif args[1] in ['-f', '--friends-timeline']:
        friends_timeline = API.GetFriendsTimeline(retweets=True)
        show_timeline(friends_timeline, 'Timeline')
    elif args[1] in ['-m', '--mentions']:
        mentions = API.GetMentions()
        show_mentions(mentions)
    elif args[1] in ['--followers']:
        followers = API.GetFollowers()
        if len(args) > 2:
            assert args[2].isdigit()
            show_followers_or_friends(followers, int(args[2]))
        else:
            show_followers_or_friends(followers)
    elif args[1] in ['--friends']:
        friends = API.GetFriends()
        if len(args) > 2:
            assert args[2].isdigit()
            show_followers_or_friends(friends, int(args[2]))
        else:
            show_followers_or_friends(friends)


def info_message(message):
    print colored(message, 'white', attrs=['bold'])


def show_help():
    print HELP
    

def main():
    if len(sys.argv) < 2:
        show_help()
    elif sys.argv[1] not in FLAGS:
        show_help()
    else:
        parse_flag(sys.argv)


if __name__ == '__main__':
    main()
    
